<?php

namespace app\common\model\server;

use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'server_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'image_str',
        'images_array',
    ];
    public function getImageStrAttr($value, $data)
    {
        if (isset($data['image']) && $data['image']) {
            return cdnurl($data['image'], true);
        }
        return '';
    }
    public function getImagesArrayAttr($value, $data)
    {
        if (isset($data['images']) && $data['images']) {
            $images = explode(',', $data['images']);
            foreach ($images as &$v) {
                $v = cdnurl($v, true);
            }
            return $images;
        }
        return [];
    }
    public function category()
    {
        return $this->belongsTo('app\common\model\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function cart()
    {
        // return $this->hasMany('app\common\model\goods\Cart', 'goods_id', 'id');
        return $this->belongsTo('app\common\model\goods\Cart', 'id', 'goods_id', [], 'LEFT')->setEagerlyType(1);

    }
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

      /**
     * 减销
     * @param int $goods_id   商品id
     * @param int $num 数量F
     */
    public static function stockUp($goods_id, $num)
    {
        return self::where('id', $goods_id)->dec('num', $num)->update();
    }
}
